<?php
/* Finding Nemo : finding missing children campaign banner
   Version 1.0

   Data update                 : sogmi, j.parker
   Server setting and managing : inureyes
   Plugin coding               : inureyes, j.parker
   Last modified at            : 2008.03.27

   License : General Public License
   Visit http://bringbring.com/entry/FootNote for the detail

   General Public License
   http://www.gnu.org/licenses/gpl.html
													     
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
*/ 

function findNemo_initConfigVal( &$data ){
	$postHeaderDefault = '<fieldset>
<legend>미아를 찾습니다</legend>';
	$postFooterDefault = '</fieldset>';
	$sidebarHeaderDefault = '<div>
<h3>미아를 찾습니다</h3>';
	$sidebarFooterDefault = '</div>';
	$data['b1'] = !isset($data['b1'])?true:$data['b1'];
	$data['b2']	= !isset($data['b2'])?true:$data['b2'];
	$data['postListLength']	 = !isset($data['postListLength'])?2:$data['postListLength'];
	$data['sidebarListLength'] = !isset($data['sidebarListLength'])?1:$data['sidebarListLength']; 
	$data['postHeader']	= !isset($data['postHeader'])?$postHeaderDefault:$data['postHeader'];
	$data['postFooter']	= !isset($data['postFooter'])?$postFooterDefault:$data['postFooter'];
	$data['sidebarHeader']	= !isset($data['sidebarHeader'])?$sidebarHeaderDefault:$data['sidebarHeader'];
	$data['sidebarFooter']	= !isset($data['sidebarFooter'])?$sidebarFooterDefault:$data['sidebarFooter'];
	$data['imageSize']	= !isset($data['imageSize'])?50:$data['imageSize'];
	$data['lineColor']	= !isset($data['lineColor'])?'#e3e3e3':$data['lineColor'];
}

function findingNemoBanner($target, $mother) {
	global $suri, $entries, $configVal;
	requireComponent('Tattertools.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	findNemo_initConfigVal($data);
	if ($suri['directive'] != "/rss" && $suri['directive'] != "/sync" && $data['b1'] && (isset($data['b3']) && !$data['b3'])) {
		$target .= '<div id="findingNemoContent'.$mother.'" class="findingNemoEntry"><script type="text/javascript">findingNemo(\''.$mother.'\');</script></div>';
	}
	return $target;
}

function findingNemoBannerTag($target) {
	global $suri, $entries, $configVal;
	requireComponent('Tattertools.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	findNemo_initConfigVal($data);
	if ($suri['directive'] != "/rss" && $suri['directive'] != "/sync" && $data['b1'] && $data['b3']) {
		$target .= '<div id="findingNemoContent[##_article_rep_id_##]" class="findingNemoEntry"><script type="text/javascript">findingNemo(\'[##_article_rep_id_##]\');</script></div>';
	}
	return $target;
}

function SB_findingNemo($parameter) {
	global $suri,  $configVal;
	requireComponent('Tattertools.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	findNemo_initConfigVal($data);	
	if (isset($parameter['preview'])) {
		$retval = "사이드바에 미아찾기 배너를 출력합니다.";
		return $retval;
	}
	if ($data['b2']) {
		$target = '<div id="findingNemoContentSidebar"><script type="text/javascript">findingNemo("Sidebar");</script></div>';
	}
	return $target;
}

function findingNemo_reader($target , $mother) {
	global $service, $configVal;
	requireComponent("Eolin.PHP.Core");
	requireComponent('Tattertools.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	findNemo_initConfigVal($data);		
	$lineColor	= (strpos($data['lineColor'], "#")===0)?$data['lineColor']:"#".$data['lineColor'];

	$_POST["idkey"] = !isset($_POST["idkey"]) ?'Sidebar':$_POST["idkey"];
	$nemoEntries = findingNemo_getXMLResource();
	if (!is_null($nemoEntries) && is_array($nemoEntries) && count($nemoEntries) > 0) {
		$contentWidth =	misc::getContentWidth();
		$target = "<div class=\"findingNemo\">";
		if($_POST["idkey"] == "Sidebar"){
			$target .= $data['sidebarHeader'];
			$listLength = $data['sidebarListLength'];
		}else{
			$target .= $data['postHeader'];
			$listLength = $data['postListLength'];
		}

		$i = 0;
		shuffle($nemoEntries);
		foreach($nemoEntries as $item) {
			preg_match('@\<img(.+)\>@isU', $item['description'], $temp);
			preg_match('/src="([^"]+)"/i', $temp[0], $temp1);
			preg_match('/width="([1-9][0-9]*)"/i', $temp[0], $temp2);
			preg_match('/height="([1-9][0-9]*)"/i', $temp[0], $temp3);
			$tempIMG = '<img src="'.$temp1[1].'" width="'.$data['imageSize'].'" onclick="findingNemoPopup(this.src,\''.$item['nemoNumber'].'\',\''.rawurldecode($item['title']).'\','.$temp2[1].','.$temp3[1].'); return false;"/>';
			$item['description'] = str_replace(array('<P>','</P>'),array('',''), $item['description']);
			$description = preg_replace('@\<div(.+)\</div>@isU', '<div class="findingNemoItem" title="크게보기"><div style="width:'.$data['imageSize'].'px;height:'.$data['imageSize'].'px;overflow:hidden;">'.$tempIMG.'</div></div>', $item['description']);
			$target .= '<div style="'.(($_POST["idkey"] == "Sidebar")?'border-bottom:1px dotted '.$lineColor.';margin:4px 0 0 0;':'float:left;width:'.(($contentWidth/2)-20).'px;margin:5px 0 0 5px;').'">'.$description.'</div>';
			if($i == ($listLength-1)) break;
			else $i++;
		}

		// TNF Needlworks & 복지재단 링크
		$nwLink = "Supported by <a href=\"http://needlworks.org/projects/findingNemo\" onclick=\"window.open(this.href); return false;\" title=\"Needlworks / Tatter Network Foundation\">Needlworks</a>";
		$msLink = "<a href=\"http://www.missingchild.or.kr\" onclick=\"window.open(this.href); return false;\" title=\"실종아동전문기관\">어린이재단</a>";
		if($_POST["idkey"] == "Sidebar"){
			$target .= "<div class=\"findingNemoInfoS\"><div class=\"findingNemoIn\">{$nwLink}<br />{$msLink}</div></div>";
			$target .= $data['sidebarFooter'];
		}else{
			$target .= "<div style=\"clear:both;border-bottom:1px dotted {$lineColor};padding-top:5px;\"></div>";
			$target .= "<div class=\"findingNemoInfoE\"><div class=\"findingNemoIn\">{$nwLink}, {$msLink}</div></div>";
			$target .= $data['postFooter'];
		}
		$target .= "</div>";
	} else {
		$target .= _t('<p>미아 정보가 없거나 가져올 수 없습니다.</p>');
	}
	unset($nemoEntries);

	header('Content-Type: text/xml; charset=UTF-8');
	echo '<?xml version="1.0" encoding="utf-8"?><response><error>0</error><findingNemoBlock><![CDATA['.$target.']]></findingNemoBlock></response>';
}
function findingNemo_getAlterUrl($link,$urlInfo){
	requireComponent('Tattertools.Function.misc');
	$attributes = misc::getAttributesFromString($link);
	if(!isset($attributes['href'])) return false;
	$rssInfo = parse_url($attributes['href']);
	$rssURL = false;
	if(isset($rssInfo['scheme']) && $rssInfo['scheme'] == 'http')
		$rssURL = $attributes['href'];
	else if(isset($rssInfo['path'])) {
		if($rssInfo['path']{0} == '/')
			$rssURL = "{$urlInfo['scheme']}://{$urlInfo['host']}{$rssInfo['path']}";							
		else
			$rssURL = "{$urlInfo['scheme']}://{$urlInfo['host']}".(isset($urlInfo['path']) ? rtrim($urlInfo['path'], '/') : '').'/'.$rssInfo['path'];
	}
	return $rssURL;
}

function findingNemo_getRemoteXml($url){
	requireComponent('Eolin.PHP.HTTPRequest');
	$request = new HTTPRequest($url);
	$request->timeout = 3;
	if (!$request->send())
		return null;
	$xml = $request->responseText;
	unset($request);
	return $xml;
}

function findingNemo_getXMLResource($url=null) {
	global $service;
	$nemoEntries = null;
	$url = is_null($url)?'http://resource.tattersite.com/findingNemo/rss':$url;	
	if(defined('__TISTORY__') ){
		$NemoCacheId = 'findingNemo_NemoCache';
		$cacheOwner = -1;
		requireComponent('Eolin.PHP.PageCache');
		$cache = new DataCache($NemoCacheId, $cacheOwner);
		if ($cache->exist()) {
			$cache->getData($nemoEntries);
			unset($cache);
		}
		unset($cache);
		return $nemoEntries;
	}
	$xml = findingNemo_getRemoteXml($url);
	if(is_null($xml)) return $nemoEntries;
	$xml = base64_decode($xml);
	$xmls = new XMLStruct();
	if (!$xmls->open($xml, $service['encoding'])) {
		if(preg_match_all('/<link .*?rel\s*=\s*[\'"]?alternate.*?>/i', $xml, $matches)) {
			$urlInfo = parse_url($url);
			foreach($matches[0] as $link) {
				$rssURL = findingNemo_getAlterUrl($link,$urlInfo);
				if($rssURL && $url != $rssURL)
					return findingNemo_getXMLResource($rssURL);
			}
		}
	}else if ($xmls->getAttribute('/rss', 'version')) {
		$nemoEntries = array();
		for ($i = 0; $link = $xmls->getValue("/rss/channel/item[$i]/link"); $i++) {
			$item = array('permalink' => rawurldecode($link));
			$item['title'] = $xmls->getValue("/rss/channel/item[$i]/title");
			$item['description'] = $xmls->getValue("/rss/channel/item[$i]/description");
			$item['nemoNumber'] = $xmls->getValue("/rss/channel/item[$i]/category");
			array_push($nemoEntries, $item);
		}
	}
	return $nemoEntries;
}

function findingNemoScript($target) {
	global $blogURL;
	$styleScript  = "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$blogURL."/plugin/findingNemoScriptStyle/?mode=style\" />".CRLF;
	$styleScript .= "<script type=\"text/javascript\" src=\"".$blogURL."/plugin/findingNemoScriptStyle/?mode=script\"></script>".CRLF;
	$target .= $styleScript;
	return $target;
}

function findingNemoScriptStyle($target){
	global $blogURL, $pluginURL, $configVal;
	requireComponent('Tattertools.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	findNemo_initConfigVal($data);
	$lineColor = (strpos($data['lineColor'], "#")===0)?$data['lineColor']:"#".$data['lineColor'];
	if($_GET['mode'] == "style"){
		header('Content-type: text/css; charset=utf-8');
		echo '
			/* finding Nemo CSS Setting */
			#findingNemoContentSidebar div {margin-top:0;}
			.findingNemo		{ margin:0px;font:8.5pt dotum, AppleGothic;}
			.findingNemo fieldset{ margin:0px; border:1px solid '.$lineColor.'; padding:0px;}

			.findingNemo legend { font-weight:bold; margin:0 0 0 5px;}
			*html .findingNemo legend { margin:0; padding:0 !important;}
			*:first-child+html .findingNemo legend { margin:0; padding:0 !important;}
			
			.findingNemo h3 { font-weight:bold; padding:0px !important;}
			.findingNemoEntry	{ margin-top:20px;}
			.findingNemoItem	{ float:left;border:1px solid '.$lineColor.';padding:2px; margin:0px 5px 0px 0px; cursor:pointer;}
			.findingNemoInfoS	{ margin:5px 0 8px 0; border:3px solid '.$lineColor.'; text-align:right;padding:5px 4px 3px 0;}
			.findingNemoInfoE	{ margin:7px 4px 5px 0; text-align:right;} 
		';
	}else if($_GET['mode'] == "script"){
		header('Content-type: text/javascript; charset=utf-8');
		echo '
			function findingNemo(id) {
				var request = new HTTPRequest("POST", "'.$blogURL.'/plugin/finding/");
				var	obj = document.getElementById("findingNemoContent" + id);
				request.onSuccess = function() {
					try {
						if (obj != null) obj.innerHTML = this.getText("/response/findingNemoBlock");
					} catch(e) { }
				}
				request.send("idkey="+id);
			}

			
			function findingNemoPopup(src, nemoNumber, name, width, height) {
				var _width	= "";
				var _height = "";
				var _left	= "";
				var _top	= "";
				var findingNemoWin = null;
				if ( findingNemoWin != null ) findingNemoWin.close();
				if(!nemoNumber){
					_width	= width;
					_height = height;
					_left	= screen.width/2-_width/2;
					_top	= (screen.height/2-_height/2)-70;
					findingNemoWin = window.open("about:blank", "findingNemo", "width="+_width+", height="+_height+", left="+_left+",top="+_top+", scrollbars=no,	status=no, resizable=no");
					findingNemoWin.document.write("<html><title>" + name + " 실종 어린이</title>");
					findingNemoWin.document.write("<meta http-equiv=\'content-type\' content=\'text/html; charset=utf-8\' />");
					findingNemoWin.document.write("<body style=\'margin:0px;\'>");
					findingNemoWin.document.write("<a href=\'javascript:self.close()\' title=\'창닫기\'><img src=\'" + src + "\' style=\'border: 0px; padding: 0; margin:0;\' /></a>");
					findingNemoWin.document.write("</body></html>");
				}else{
					_width  = 516;
					_height = 500;
					_left	= screen.width/2-_width/2;
					_top	= (screen.height/2-_height/2)-70;
					findingNemoWin = window.open("'.$blogURL.'/plugin/findingNemoShow/?ambno="+nemoNumber+"&name="+encodeURIComponent(name), "findingNemo", "width="+_width+", height="+_height+", left="+_left+",top="+_top+", scrollbars=yes, status=no, resizable=yes");				
				}
				findingNemoWin.focus();

			}
		';
	}
	flush();
}

function findingNemoShow($target){
	global $pluginURL;
	requireComponent('Eolin.PHP.HTTPRequest');

	if(isset($_GET['ambno']) && !empty($_GET['ambno'])){
		$ambNo = $_GET['ambno'];
		$ambNm = $_GET['name'];
		$nemoHost = "http://www.missingchild.or.kr/child_search/report_detail.asp";
		$queryString = "ambno=" . $ambNo . "&p_mode=1";
		$request = new HTTPRequest('POST', $nemoHost);
		$request->contentType = "application/x-www-form-urlencoded; charset=UTF-8";
		$request->send($queryString);
		$result = $request->responseText;
		$chkTable = preg_match_all("@<table.+width=['\"]530['\"].+>(.*)</table>@isU", $result, $tmpTable);
		$newTable = preg_replace(array("@ style=['\"](.+)['\"]@isU", "@width=['\"]530['\"]@isU", "@ height=['\"](.+)['\"]@isU"), array("", "width=\"464\"", " class=\"nemoImg\""), iconv("EUC-KR", "UTF-8", $tmpTable[0][1]));
		$newTable = str_replace(array("\t", "<br><br><br>", "<br><br>" ,"   "),array("", "<br>", "<br>", ""), $newTable);
		
		$html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'.CRLF;
		$html .= "<html xmlns=\"http://www.w3.org/1999/xhtml\">".CRLF;
		$html .= "<head>".CRLF;
		$html .= "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />".CRLF;
		$html .= "<title>" . $ambNm . " 실종 어린이</title>".CRLF;
		$html .= "</head>".CRLF;
		$html .= "<style type=\"text/css\">".CRLF;
		$html .= " body {margin:0px;font: 1.2em/1.7 AppleGothic, Gulim, '굴림', Helvetica, sans-serif;font-size: 75%;}".CRLF;
		$html .= " .nemoImg{border:5px solid #e7e7e7;margin-bottom:5px;}".CRLF;
		$html .= "</style>".CRLF;
		$html .= "<body>".CRLF;
		$html .= "<table id='Table_01' width='500' border='0' cellpadding='0' cellspacing='0'>".CRLF;
		$html .= "	<tr height='78'><td><img id='findingnemo_img_01' src='{$pluginURL}/images/findingnemo_img_01.gif' width='500' height='78' alt='' /></td></tr>".CRLF;
		$html .= "	<tr height='368'>".CRLF;
		$html .= "		<td background='{$pluginURL}/images/findingnemo_img_02.gif' style='padding-left:18px;' valign='top'>".CRLF;
		$html .=		$newTable.CRLF;
		$html .= "		</td>".CRLF;
		$html .= "	</tr>".CRLF;
		$html .= "	<tr height='28'>".CRLF;
		$html .= "		<td background='{$pluginURL}/images/findingnemo_img_02.gif' align='center' valign='bottom' style='font-size:1px;'>".CRLF;
		$html .= "			<a href='http://www.missingchild.or.kr/child_furnish/ChildFurnish.asp' onclick='opener.window.open(this.href); return false;' title='' style='margin-right:5px;'><img src='{$pluginURL}/images/findingnemo_btn_call.gif' border='0' alt='' /></a>".CRLF;
		$html .= "			<a href='#' onclick='self.close();' title=''><img src='{$pluginURL}/images/findingnemo_btn_close.gif' border='0' alt='' /></a>".CRLF;
		$html .= "		</td>".CRLF;
		$html .= "	</tr>".CRLF;
		$html .= "	<tr height='28'><td><img id='findingnemo_img_03' src='{$pluginURL}/images/findingnemo_img_03.gif' width='500' height='28' alt='' /></td></tr>".CRLF;
		$html .= "</table>".CRLF;
		$html .= "</body>".CRLF;
		$html .= "</html>";

		header('Content-Type: text/html; charset=UTF-8');
		echo $html;
		flush();
	}
}

function findingNemo_DataSet($DATA){
	requireComponent('Tattertools.Function.misc');
	$cfg = misc::fetchConfigVal($DATA);
	return true;
}
?>
